package cn.zjj.org.controller;

import cn.zjj.basic.anno.PreAuthorize;
import cn.zjj.basic.util.JsonResult;
import cn.zjj.basic.util.PageList;
import cn.zjj.org.domain.Department;
import cn.zjj.org.query.DepartmentQuery;
import cn.zjj.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/department")
@Api(value = "部门的API",description="部门相关的CRUD功能")
public class DepartmentController {

    @Resource
    private IDepartmentService departmentService;

    //部门树
    @GetMapping("/deptTree")
    @PreAuthorize(name = "部门树",value = "department:tree")
    public List<Department> deptTree(){
        return departmentService.deptTree();
    }


    //查询所有
    @GetMapping
    @ApiOperation(value = "查询所有数据" )
    @PreAuthorize(name = "部门列表",value = "department:list")
    public List<Department> selectAll(){

        return departmentService.selectAll();
    }

    //查询单个
    @GetMapping("/{id}")
    @ApiOperation(value = "查询一条数据" )
    @PreAuthorize(name = "查询部门",value = "department:get")
    public Department selectById(@PathVariable("id") Long id){
        return departmentService.selectById(id);
    }

    //删除单个
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除一个数据" )
    @PreAuthorize(name = "删除部门",value = "department:delete")
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            departmentService.delete(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false,"操作失败");
        }
    }

    //添加或修改
    @PutMapping
    @ApiOperation(value = "添加或修改数据" )
    @PreAuthorize(name = "部门保存",value = "department:save")
    public JsonResult updateOrAdd(@RequestBody Department department){
        try {
            if(department.getId()==null){
                departmentService.insert(department);
            }else {
                departmentService.update(department);
            }
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false,"操作失败");
        }
    }

    //分页和高级查询
    @PostMapping
    @ApiOperation(value = "分页查询或高级查询" )
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query){
        return departmentService.selectQuery(query);
    }

    @PatchMapping
    @ApiOperation(value = "批量删除" )
    @PreAuthorize(name = "部门批量删除",value = "department:patchDel")
    public JsonResult delete(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me(false,"操作失败");
        }
    }
}
